<template>
  <div class="p-6">
    <!-- Tab切换 -->
    <div class="glass-effect rounded-2xl p-2 mb-6 shadow-pink-md">
      <div class="grid grid-cols-3 gap-2">
        <div
          v-for="tab in tabs"
          :key="tab.key"
          class="py-3 px-4 rounded-xl text-center cursor-pointer transition-all duration-300"
          :class="
            activeTab === tab.key
              ? 'bg-gradient-to-r from-pink-400 to-pink-500 text-white shadow-pink-md'
              : 'text-pink-400 hover:bg-pink-50'
          "
          @click="activeTab = tab.key"
        >
          <span class="text-xl mr-1">{{ tab.icon }}</span>
          <span class="font-medium">{{ tab.label }}</span>
        </div>
      </div>
    </div>

    <!-- 日程列表 -->
    <div v-if="activeTab === 'schedules'" class="space-y-4">
      <!-- 分类筛选 -->
      <div class="glass-effect rounded-2xl p-2 shadow-pink-md overflow-x-auto">
        <div class="flex gap-1.5 flex-nowrap">
          <n-tag
            v-for="category in categories"
            :key="category.key"
            :type="selectedCategory === category.key ? 'primary' : 'default'"
            :bordered="false"
            size="small"
            class="cursor-pointer whitespace-nowrap text-xs px-2 py-0.5"
            @click="selectedCategory = category.key"
          >
            <span class="text-sm mr-0.5">{{ category.icon }}</span>
            <span>{{ category.label }}</span>
          </n-tag>
        </div>
      </div>

      <!-- 添加按钮 -->
      <div class="flex justify-end">
        <n-button type="primary" size="large" class="rounded-xl" @click="handleAddSchedule">
          + 添加日程
        </n-button>
      </div>

      <!-- 日程列表 -->
      <div class="space-y-3">
        <div
          v-for="schedule in filteredSchedules"
          :key="schedule.id"
          class="glass-effect rounded-2xl p-5 shadow-pink-md"
        >
          <div class="flex items-start gap-4">
            <div class="flex-shrink-0 text-3xl">{{ schedule.icon }}</div>
            <div class="flex-1">
              <div class="flex items-start justify-between mb-2">
                <div>
                  <h4 class="text-lg font-bold text-pink-600">{{ schedule.title }}</h4>
                  <p class="text-sm text-pink-400 mt-1">📅 {{ schedule.date }}</p>
                  <n-tag
                    size="small"
                    :type="schedule.completed ? 'success' : 'warning'"
                    :bordered="false"
                    class="mt-2"
                  >
                    {{ schedule.completed ? '✓ 已完成' : '⏰ 进行中' }}
                  </n-tag>
                </div>
                <div class="flex gap-2">
                  <n-button size="small" tertiary @click="toggleComplete(schedule)">
                    {{ schedule.completed ? '撤销' : '完成' }}
                  </n-button>
                  <n-button size="small" tertiary @click="handleEditSchedule(schedule)">
                    编辑
                  </n-button>
                  <n-button size="small" tertiary type="error" @click="handleDeleteSchedule(schedule.id)">
                    删除
                  </n-button>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- 纪念日 -->
    <div v-if="activeTab === 'anniversaries'" class="space-y-4">
      <!-- 添加按钮 -->
      <div class="flex justify-end">
        <n-button type="primary" size="large" class="rounded-xl" @click="handleAddAnniversary">
          + 添加纪念日
        </n-button>
      </div>

      <!-- 纪念日列表 -->
      <div class="space-y-4">
        <div
          v-for="anniversary in anniversaries"
          :key="anniversary.id"
          class="glass-effect rounded-3xl p-6 shadow-pink-xl text-center relative"
        >
          <div class="absolute top-4 right-4 flex gap-2">
            <n-button size="tiny" tertiary @click="handleEditAnniversary(anniversary)">
              编辑
            </n-button>
            <n-button size="tiny" tertiary type="error" @click="handleDeleteAnniversary(anniversary.id)">
              删除
            </n-button>
          </div>
          <div class="text-5xl mb-3">{{ anniversary.icon }}</div>
          <h3 class="text-xl font-bold text-pink-600 mb-2">{{ anniversary.title }}</h3>
          <p class="text-pink-400 mb-4">{{ anniversary.date }}</p>
          <div class="bg-pink-50 rounded-2xl p-4">
            <div class="text-4xl font-bold text-pink-500 mb-1">{{ anniversary.daysCount }}</div>
            <p class="text-sm text-pink-400">天后</p>
          </div>
        </div>
      </div>
    </div>

    <!-- 见面计划 -->
    <div v-if="activeTab === 'meetings'" class="space-y-4">
      <!-- 下次见面倒计时 -->
      <div class="glass-effect rounded-3xl p-8 shadow-pink-xl text-center">
        <h3 class="text-2xl font-bold text-pink-600 mb-6">下次见面倒计时</h3>
        <div class="flex items-center justify-center gap-4 mb-4">
          <div class="flex flex-col items-center">
            <span class="text-5xl font-bold text-pink-500">{{ nextMeeting.days }}</span>
            <span class="text-sm text-pink-400 mt-1">天</span>
          </div>
          <span class="text-3xl text-pink-300">:</span>
          <div class="flex flex-col items-center">
            <span class="text-5xl font-bold text-pink-500">{{ nextMeeting.hours }}</span>
            <span class="text-sm text-pink-400 mt-1">时</span>
          </div>
          <span class="text-3xl text-pink-300">:</span>
          <div class="flex flex-col items-center">
            <span class="text-5xl font-bold text-pink-500">{{ nextMeeting.minutes }}</span>
            <span class="text-sm text-pink-400 mt-1">分</span>
          </div>
        </div>
        <p class="text-pink-400">{{ nextMeeting.date }} · {{ nextMeeting.location }}</p>
        <n-button type="primary" size="large" class="rounded-xl mt-6" @click="handleEditMeeting">
          编辑见面计划
        </n-button>
      </div>

      <!-- 见面统计 -->
      <div class="glass-effect rounded-2xl p-6 shadow-pink-md">
        <h3 class="text-xl font-bold text-pink-600 mb-4">见面统计</h3>
        <div class="grid grid-cols-2 gap-4">
          <div class="text-center bg-pink-50 rounded-xl p-4">
            <p class="text-3xl font-bold text-pink-500">{{ meetingStats.total }}</p>
            <p class="text-sm text-pink-400 mt-1">总见面次数</p>
          </div>
          <div class="text-center bg-pink-50 rounded-xl p-4">
            <p class="text-3xl font-bold text-pink-500">{{ meetingStats.thisYear }}</p>
            <p class="text-sm text-pink-400 mt-1">今年见面</p>
          </div>
        </div>
      </div>

      <!-- 历史见面记录 -->
      <div class="glass-effect rounded-2xl p-6 shadow-pink-md">
        <div class="flex items-center justify-between mb-4">
          <h3 class="text-xl font-bold text-pink-600">历史见面记录</h3>
          <n-button type="primary" size="small" class="rounded-xl" @click="handleAddMeetingRecord">
            + 添加
          </n-button>
        </div>
        <div class="space-y-3">
          <div
            v-for="record in meetingRecords"
            :key="record.id"
            class="bg-white/50 rounded-xl p-4 flex items-center gap-4"
          >
            <div class="text-3xl">{{ record.icon }}</div>
            <div class="flex-1">
              <p class="font-medium text-pink-600">{{ record.title }}</p>
              <p class="text-sm text-pink-400 mt-1">{{ record.date }}</p>
            </div>
            <div class="flex gap-2">
              <n-button size="tiny" tertiary @click="handleEditMeetingRecord(record)">
                编辑
              </n-button>
              <n-button size="tiny" tertiary type="error" @click="handleDeleteMeetingRecord(record.id)">
                删除
              </n-button>
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- 回收站 -->
    <div v-if="activeTab === 'trash'" class="space-y-4">
      <div v-if="deletedSchedules.length === 0" class="text-center py-12">
        <div class="text-8xl mb-4">🗑️</div>
        <p class="text-pink-400 text-lg">回收站是空的</p>
        <p class="text-pink-300 text-sm mt-2">已删除的日程会保留在这里</p>
      </div>

      <div v-else class="space-y-3">
        <div
          v-for="schedule in deletedSchedules"
          :key="schedule.id"
          class="glass-effect rounded-2xl p-5 shadow-pink-md opacity-75"
        >
          <div class="flex items-start gap-4">
            <div class="flex-shrink-0 text-3xl grayscale">{{ schedule.icon }}</div>
            <div class="flex-1">
              <div class="flex items-start justify-between mb-2">
                <div>
                  <h4 class="text-lg font-bold text-pink-600 line-through">{{ schedule.title }}</h4>
                  <p class="text-sm text-pink-400 mt-1">📅 {{ schedule.date }}</p>
                  <n-tag size="small" type="default" :bordered="false" class="mt-2">
                    已删除
                  </n-tag>
                </div>
                <div class="flex gap-2">
                  <n-button size="small" tertiary type="success" @click="handleRestoreSchedule(schedule.id)">
                    恢复
                  </n-button>
                  <n-button size="small" tertiary type="error" @click="handlePermanentDeleteSchedule(schedule.id)">
                    永久删除
                  </n-button>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- 添加/编辑日程模态框 -->
    <n-modal v-model:show="showScheduleModal">
      <div class="glass-effect rounded-3xl p-8 max-w-md w-full shadow-pink-xl">
        <h3 class="text-2xl font-bold text-pink-600 mb-6">
          {{ scheduleForm.id ? '编辑日程' : '添加日程' }}
        </h3>
        <n-form ref="scheduleFormRef" :model="scheduleForm" :rules="scheduleRules">
          <n-form-item label="标题" path="title">
            <n-input v-model:value="scheduleForm.title" placeholder="输入日程标题" />
          </n-form-item>
          <n-form-item label="日期" path="dateValue">
            <n-date-picker v-model:value="scheduleForm.dateValue" type="date" class="w-full" />
          </n-form-item>
          <n-form-item label="分类" path="category">
            <n-select
              v-model:value="scheduleForm.category"
              :options="categories.filter(c => c.key !== 'all').map(c => ({ label: c.label, value: c.key }))"
            />
          </n-form-item>
          <n-form-item label="图标">
            <div class="flex gap-2 flex-wrap">
              <span
                v-for="emoji in scheduleEmojis"
                :key="emoji"
                class="text-2xl cursor-pointer hover:scale-125 transition-all"
                :class="scheduleForm.icon === emoji ? 'scale-125' : ''"
                @click="scheduleForm.icon = emoji"
              >
                {{ emoji }}
              </span>
            </div>
          </n-form-item>
          <div class="flex gap-3">
            <n-button type="primary" size="large" block class="rounded-xl" @click="handleSaveSchedule">
              {{ scheduleForm.id ? '保存' : '添加' }}
            </n-button>
            <n-button size="large" block class="rounded-xl" @click="showScheduleModal = false">
              取消
            </n-button>
          </div>
        </n-form>
      </div>
    </n-modal>

    <!-- 添加/编辑纪念日模态框 -->
    <n-modal v-model:show="showAnniversaryModal">
      <div class="glass-effect rounded-3xl p-8 max-w-md w-full shadow-pink-xl">
        <h3 class="text-2xl font-bold text-pink-600 mb-6">
          {{ anniversaryForm.id ? '编辑纪念日' : '添加纪念日' }}
        </h3>
        <n-form ref="anniversaryFormRef" :model="anniversaryForm" :rules="anniversaryRules">
          <n-form-item label="名称" path="title">
            <n-input v-model:value="anniversaryForm.title" placeholder="如：恋爱纪念日" />
          </n-form-item>
          <n-form-item label="日期" path="dateValue">
            <n-date-picker v-model:value="anniversaryForm.dateValue" type="date" class="w-full" />
          </n-form-item>
          <n-form-item label="图标">
            <div class="flex gap-2 flex-wrap">
              <span
                v-for="emoji in anniversaryEmojis"
                :key="emoji"
                class="text-3xl cursor-pointer hover:scale-125 transition-all"
                :class="anniversaryForm.icon === emoji ? 'scale-125' : ''"
                @click="anniversaryForm.icon = emoji"
              >
                {{ emoji }}
              </span>
            </div>
          </n-form-item>
          <div class="flex gap-3">
            <n-button type="primary" size="large" block class="rounded-xl" @click="handleSaveAnniversary">
              {{ anniversaryForm.id ? '保存' : '添加' }}
            </n-button>
            <n-button size="large" block class="rounded-xl" @click="showAnniversaryModal = false">
              取消
            </n-button>
          </div>
        </n-form>
      </div>
    </n-modal>

    <!-- 编辑见面计划模态框 -->
    <n-modal v-model:show="showMeetingModal">
      <div class="glass-effect rounded-3xl p-8 max-w-md w-full shadow-pink-xl">
        <h3 class="text-2xl font-bold text-pink-600 mb-6">编辑见面计划</h3>
        <n-form ref="meetingFormRef" :model="meetingForm" :rules="meetingRules">
          <n-form-item label="日期" path="dateValue">
            <n-date-picker v-model:value="meetingForm.dateValue" type="date" class="w-full" />
          </n-form-item>
          <n-form-item label="地点" path="location">
            <n-input v-model:value="meetingForm.location" placeholder="见面地点" />
          </n-form-item>
          <div class="flex gap-3">
            <n-button type="primary" size="large" block class="rounded-xl" @click="handleSaveMeeting">
              保存
            </n-button>
            <n-button size="large" block class="rounded-xl" @click="showMeetingModal = false">
              取消
            </n-button>
          </div>
        </n-form>
      </div>
    </n-modal>

    <!-- 添加/编辑见面记录模态框 -->
    <n-modal v-model:show="showMeetingRecordModal">
      <div class="glass-effect rounded-3xl p-8 max-w-md w-full shadow-pink-xl">
        <h3 class="text-2xl font-bold text-pink-600 mb-6">
          {{ meetingRecordForm.id ? '编辑记录' : '添加见面记录' }}
        </h3>
        <n-form ref="meetingRecordFormRef" :model="meetingRecordForm" :rules="meetingRecordRules">
          <n-form-item label="标题" path="title">
            <n-input v-model:value="meetingRecordForm.title" placeholder="如：周末游乐园" />
          </n-form-item>
          <n-form-item label="日期" path="dateValue">
            <n-date-picker v-model:value="meetingRecordForm.dateValue" type="date" class="w-full" />
          </n-form-item>
          <n-form-item label="图标">
            <div class="flex gap-2 flex-wrap">
              <span
                v-for="emoji in meetingEmojis"
                :key="emoji"
                class="text-2xl cursor-pointer hover:scale-125 transition-all"
                :class="meetingRecordForm.icon === emoji ? 'scale-125' : ''"
                @click="meetingRecordForm.icon = emoji"
              >
                {{ emoji }}
              </span>
            </div>
          </n-form-item>
          <div class="flex gap-3">
            <n-button type="primary" size="large" block class="rounded-xl" @click="handleSaveMeetingRecord">
              {{ meetingRecordForm.id ? '保存' : '添加' }}
            </n-button>
            <n-button size="large" block class="rounded-xl" @click="showMeetingRecordModal = false">
              取消
            </n-button>
          </div>
        </n-form>
      </div>
    </n-modal>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted, onUnmounted } from 'vue'
import { useMessage, useDialog, type FormInst, type FormRules } from 'naive-ui'
import { useAuthStore } from '@/stores/auth'
import type { Schedule } from '@/types/schedule'
import type { Countdown } from '@/types/countdown'
import type { Anniversary } from '@/types/anniversary'
import type { RelationshipStat } from '@/types/relationship'
import * as scheduleApi from '@/api/schedule'
import * as countdownApi from '@/api/countdown'
import * as anniversaryApi from '@/api/anniversary'
import * as relationshipApi from '@/api/relationship'

const message = useMessage()
const dialog = useDialog()
const authStore = useAuthStore()

// 加载状态
const loading = ref(false)

// Tab配置
const tabs = [
  { key: 'schedules', label: '日程', icon: '📅' },
  { key: 'anniversaries', label: '纪念日', icon: '🎂' },
  { key: 'meetings', label: '见面', icon: '✈️' },
  { key: 'trash', label: '回收站', icon: '🗑️' },
]

const activeTab = ref('schedules')

// ============ 日程相关 ============
const categories = [
  { key: 'all', label: '全部', icon: '📋' },
  { key: '约会', label: '约会', icon: '💖' },
  { key: '工作', label: '工作', icon: '💼' },
  { key: '纪念日', label: '纪念日', icon: '🎂' },
  { key: '其他', label: '其他', icon: '📅' },
]

const selectedCategory = ref('all')

// 原始日程数据
const schedulesData = ref<Schedule[]>([])
const deletedSchedulesData = ref<Schedule[]>([]) // 已删除的日程数据

// 根据分类映射图标
const getCategoryIcon = (category: string): string => {
  const iconMap: Record<string, string> = {
    约会: '💖',
    工作: '💼',
    纪念日: '🎂',
    其他: '📅',
  }
  return iconMap[category] || '📅'
}

// 转换后端数据为前端展示格式
const schedules = computed(() => {
  return schedulesData.value.map((schedule) => ({
    id: schedule.id,
    icon: getCategoryIcon(schedule.category),
    title: schedule.title,
    date: schedule.deadline.split('T')[0],
    category: schedule.category,
    completed: schedule.status === '已完成',
    deleted: false,
    _raw: schedule,
  }))
})

const filteredSchedules = computed(() => {
  if (selectedCategory.value === 'all') {
    return schedules.value
  }
  return schedules.value.filter((s) => s.category === selectedCategory.value)
})

// 已删除的日程
const deletedSchedules = computed(() => {
  return deletedSchedulesData.value.map((schedule) => ({
    id: schedule.id,
    icon: getCategoryIcon(schedule.category),
    title: schedule.title,
    date: schedule.deadline.split('T')[0],
    category: schedule.category,
    completed: schedule.status === '已完成',
    deleted: true,
    _raw: schedule,
  }))
})

const toggleComplete = async (schedule: any) => {
  try {
    const rawSchedule = schedule._raw as Schedule
    const newStatus = schedule.completed ? '未完成' : '已完成'

    await scheduleApi.updateSchedule(schedule.id, {
      status: newStatus,
    })

    schedule.completed = !schedule.completed
    message.success(schedule.completed ? '已标记为完成' : '已取消完成')

    // 更新本地数据
    await loadSchedules()
  } catch (error: any) {
    console.error('更新状态失败:', error)
    message.error('更新失败')
  }
}

// 日程表单
const showScheduleModal = ref(false)
const scheduleFormRef = ref<FormInst | null>(null)
const scheduleForm = ref({
  id: null as number | null,
  title: '',
  dateValue: null as number | null,
  category: '约会',
  icon: '📅',
})

const scheduleEmojis = ['📅', '💖', '📞', '🎁', '🎂', '💼', '🎉', '✈️', '🍰', '🎡']

const scheduleRules: FormRules = {
  title: [{ required: true, message: '请输入标题', trigger: 'blur' }],
  dateValue: [{ required: true, message: '请选择日期', trigger: 'blur', type: 'number' }],
  category: [{ required: true, message: '请选择分类', trigger: 'change' }],
}

const handleAddSchedule = () => {
  scheduleForm.value = {
    id: null,
    title: '',
    dateValue: null,
    category: '约会',
    icon: '📅',
  }
  showScheduleModal.value = true
}

const handleEditSchedule = (schedule: any) => {
  const rawSchedule = schedule._raw as Schedule
  scheduleForm.value = {
    id: schedule.id,
    title: schedule.title,
    dateValue: new Date(rawSchedule.deadline).getTime(),
    category: schedule.category,
    icon: schedule.icon,
  }
  showScheduleModal.value = true
}

const handleSaveSchedule = async () => {
  if (!scheduleFormRef.value) return
  try {
    await scheduleFormRef.value.validate()

    const userId = authStore.userInfo?.id
    if (!userId) {
      message.error('请先登录')
      return
    }

    // 格式化日期为后端要求的格式 "2006-01-02 15:04:05"
    const date = new Date(scheduleForm.value.dateValue!)
    const deadline = `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')} 00:00:00`

    if (scheduleForm.value.id) {
      // 编辑
      await scheduleApi.updateSchedule(scheduleForm.value.id, {
        title: scheduleForm.value.title,
        deadline,
        category: scheduleForm.value.category,
      })
      message.success('日程更新成功')
    } else {
      // 新增
      await scheduleApi.createSchedule({
        title: scheduleForm.value.title,
        deadline,
        category: scheduleForm.value.category,
        creator_id: userId,
      })
      message.success('日程添加成功')
    }

    showScheduleModal.value = false
    await loadSchedules()
  } catch (error: any) {
    console.error('保存日程失败:', error)
  }
}

const handleDeleteSchedule = (id: number) => {
  dialog.warning({
    title: '确认删除',
    content: '删除后可在回收站中恢复',
    positiveText: '删除',
    negativeText: '取消',
    onPositiveClick: async () => {
      try {
        await scheduleApi.deleteSchedule(id)
        message.success('已移至回收站')
        // 重新加载数据
        await Promise.all([loadSchedules(), loadDeletedSchedules()])
      } catch (error: any) {
        console.error('删除失败:', error)
        message.error('删除失败')
      }
    },
  })
}

// 恢复日程
const handleRestoreSchedule = (id: number) => {
  dialog.info({
    title: '确认恢复',
    content: '确定要恢复这个日程吗？',
    positiveText: '恢复',
    negativeText: '取消',
    onPositiveClick: async () => {
      try {
        await scheduleApi.restoreSchedule(id)
        message.success('日程已恢复')
        // 重新加载数据
        await Promise.all([loadSchedules(), loadDeletedSchedules()])
      } catch (error: any) {
        console.error('恢复失败:', error)
        message.error('恢复失败')
      }
    },
  })
}

// 永久删除日程
const handlePermanentDeleteSchedule = (id: number) => {
  dialog.error({
    title: '确认永久删除',
    content: '永久删除后无法恢复，确定要删除吗？',
    positiveText: '永久删除',
    negativeText: '取消',
    onPositiveClick: async () => {
      try {
        await scheduleApi.permanentDeleteSchedule(id)
        message.success('已永久删除')
        // 重新加载已删除数据
        await loadDeletedSchedules()
      } catch (error: any) {
        console.error('永久删除失败:', error)
        message.error('删除失败')
      }
    },
  })
}

// ============ 纪念日相关 ============
const anniversariesData = ref<Anniversary[]>([])

// 转换纪念日数据
const anniversaries = computed(() => {
  return anniversariesData.value.map((anniversary) => {
    const targetDate = new Date(anniversary.date).getTime()
    const now = Date.now()
    const daysCount = Math.ceil((targetDate - now) / (1000 * 60 * 60 * 24))

    return {
      id: anniversary.id,
      icon: getAnniversaryIcon(anniversary.type),
      title: anniversary.title,
      date: anniversary.date.split('T')[0],
      daysCount: daysCount > 0 ? daysCount : 0,
      _raw: anniversary,
    }
  })
})

const getAnniversaryIcon = (type: string): string => {
  const iconMap: Record<string, string> = {
    恋爱纪念日: '💕',
    生日: '🎂',
    第一次见面: '💑',
    其他: '💝',
  }
  return iconMap[type] || '💝'
}

const showAnniversaryModal = ref(false)
const anniversaryFormRef = ref<FormInst | null>(null)
const anniversaryForm = ref({
  id: null as number | null,
  title: '',
  dateValue: null as number | null,
  icon: '💕',
})

const anniversaryEmojis = ['💕', '🎂', '💑', '💝', '❤️', '💖', '🎉', '🌸']

const anniversaryRules: FormRules = {
  title: [{ required: true, message: '请输入名称', trigger: 'blur' }],
  dateValue: [{ required: true, message: '请选择日期', trigger: 'blur', type: 'number' }],
}

const handleAddAnniversary = () => {
  anniversaryForm.value = {
    id: null,
    title: '',
    dateValue: null,
    icon: '💕',
  }
  showAnniversaryModal.value = true
}

const handleEditAnniversary = (anniversary: any) => {
  anniversaryForm.value = {
    id: anniversary.id,
    title: anniversary.title,
    dateValue: new Date(anniversary.date).getTime(),
    icon: anniversary.icon,
  }
  showAnniversaryModal.value = true
}

const handleSaveAnniversary = async () => {
  if (!anniversaryFormRef.value) return
  try {
    await anniversaryFormRef.value.validate()
    const dateStr = new Date(anniversaryForm.value.dateValue!).toISOString().split('T')[0]

    // 根据图标推测类型
    const iconTypeMap: Record<string, string> = {
      '💕': '恋爱纪念日',
      '💑': '恋爱纪念日',
      '🎂': '生日',
      '💖': '其他',
      '❤️': '其他',
    }
    const type = iconTypeMap[anniversaryForm.value.icon] || '其他'

    if (anniversaryForm.value.id) {
      await anniversaryApi.updateAnniversary(anniversaryForm.value.id, {
        title: anniversaryForm.value.title,
        date: dateStr,
        type,
      })
      message.success('纪念日更新成功')
    } else {
      await anniversaryApi.createAnniversary({
        title: anniversaryForm.value.title,
        date: dateStr,
        type,
      })
      message.success('纪念日添加成功')
    }

    showAnniversaryModal.value = false
    await loadAnniversaries()
  } catch (error: any) {
    console.error('保存纪念日失败:', error)
  }
}

const handleDeleteAnniversary = (id: number) => {
  dialog.warning({
    title: '确认删除',
    content: '确定要删除这个纪念日吗？',
    positiveText: '删除',
    negativeText: '取消',
    onPositiveClick: async () => {
      try {
        await anniversaryApi.deleteAnniversary(id)
        await loadAnniversaries()
        message.success('纪念日已删除')
      } catch (error: any) {
        console.error('删除纪念日失败:', error)
        message.error('删除失败')
      }
    },
  })
}

// ============ 见面计划相关 ============
const meetingCountdownData = ref<Countdown | null>(null)
const relationshipStatData = ref<RelationshipStat | null>(null)

let meetingTimer: number | null = null

// 计算下次见面倒计时
const nextMeeting = computed(() => {
  if (!meetingCountdownData.value) {
    return {
      days: 0,
      hours: 0,
      minutes: 0,
      date: '',
      location: '暂无见面计划',
    }
  }

  const now = new Date().getTime()
  const target = new Date(meetingCountdownData.value.target_date).getTime()
  const diff = target - now

  if (diff <= 0) {
    return {
      days: 0,
      hours: 0,
      minutes: 0,
      date: meetingCountdownData.value.target_date.split('T')[0],
      location: meetingCountdownData.value.description || '见面计划',
    }
  }

  const days = Math.floor(diff / (1000 * 60 * 60 * 24))
  const hours = Math.floor((diff % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60))
  const minutes = Math.floor((diff % (1000 * 60 * 60)) / (1000 * 60))

  return {
    days,
    hours,
    minutes,
    date: meetingCountdownData.value.target_date.split('T')[0],
    location: meetingCountdownData.value.description || '见面计划',
  }
})

// 见面统计
const meetingStats = computed(() => {
  if (!relationshipStatData.value) {
    return {
      total: 0,
      thisYear: 0,
    }
  }

  const currentYear = new Date().getFullYear()
  const firstMeetDate = relationshipStatData.value.first_meet_date
    ? new Date(relationshipStatData.value.first_meet_date)
    : null

  // 简化计算：如果第一次见面是今年，则今年见面次数等于总次数
  const thisYear =
    firstMeetDate && firstMeetDate.getFullYear() === currentYear
      ? relationshipStatData.value.meet_count
      : 0

  return {
    total: relationshipStatData.value.meet_count,
    thisYear,
  }
})

// 暂时不接入历史见面记录（可以后续扩展）
const meetingRecords = ref([
  {
    id: 1,
    icon: '🎡',
    title: '周末游乐园',
    date: '2025-09-15',
  },
  {
    id: 2,
    icon: '🍿',
    title: '一起看电影',
    date: '2025-08-20',
  },
])

// 编辑下次见面
const showMeetingModal = ref(false)
const meetingFormRef = ref<FormInst | null>(null)
const meetingForm = ref({
  dateValue: null as number | null,
  location: '',
})

const meetingRules: FormRules = {
  dateValue: [{ required: true, message: '请选择日期', trigger: 'blur', type: 'number' }],
  location: [{ required: true, message: '请输入地点', trigger: 'blur' }],
}

const handleEditMeeting = () => {
  meetingForm.value = {
    dateValue: new Date(nextMeeting.value.date).getTime(),
    location: nextMeeting.value.location,
  }
  showMeetingModal.value = true
}

const handleSaveMeeting = async () => {
  if (!meetingFormRef.value) return
  try {
    await meetingFormRef.value.validate()
    const dateStr = new Date(meetingForm.value.dateValue!).toISOString().split('T')[0]
    nextMeeting.value.date = dateStr
    nextMeeting.value.location = meetingForm.value.location
    message.success('见面计划已更新')
    showMeetingModal.value = false
  } catch (error) {
    // 表单验证失败
  }
}

// 见面记录
const showMeetingRecordModal = ref(false)
const meetingRecordFormRef = ref<FormInst | null>(null)
const meetingRecordForm = ref({
  id: null as number | null,
  title: '',
  dateValue: null as number | null,
  icon: '🎡',
})

const meetingEmojis = ['🎡', '🍿', '🍰', '🎬', '🎸', '🎮', '🏖️', '🗼']

const meetingRecordRules: FormRules = {
  title: [{ required: true, message: '请输入标题', trigger: 'blur' }],
  dateValue: [{ required: true, message: '请选择日期', trigger: 'blur', type: 'number' }],
}

const handleAddMeetingRecord = () => {
  meetingRecordForm.value = {
    id: null,
    title: '',
    dateValue: null,
    icon: '🎡',
  }
  showMeetingRecordModal.value = true
}

const handleEditMeetingRecord = (record: any) => {
  meetingRecordForm.value = {
    id: record.id,
    title: record.title,
    dateValue: new Date(record.date).getTime(),
    icon: record.icon,
  }
  showMeetingRecordModal.value = true
}

const handleSaveMeetingRecord = async () => {
  if (!meetingRecordFormRef.value) return
  try {
    await meetingRecordFormRef.value.validate()
    const dateStr = new Date(meetingRecordForm.value.dateValue!).toISOString().split('T')[0]

    if (meetingRecordForm.value.id) {
      const index = meetingRecords.value.findIndex((r) => r.id === meetingRecordForm.value.id)
      if (index !== -1) {
        meetingRecords.value[index] = {
          ...meetingRecords.value[index],
          title: meetingRecordForm.value.title,
          date: dateStr,
          icon: meetingRecordForm.value.icon,
        }
        message.success('记录更新成功')
      }
    } else {
      meetingRecords.value.push({
        id: Date.now(),
        title: meetingRecordForm.value.title,
        date: dateStr,
        icon: meetingRecordForm.value.icon,
      })
      message.success('记录添加成功')
      meetingStats.value.total++
    }
    showMeetingRecordModal.value = false
  } catch (error) {
    // 表单验证失败
  }
}

const handleDeleteMeetingRecord = (id: number) => {
  dialog.warning({
    title: '确认删除',
    content: '确定要删除这条见面记录吗？',
    positiveText: '删除',
    negativeText: '取消',
    onPositiveClick: () => {
      const index = meetingRecords.value.findIndex((r) => r.id === id)
      if (index !== -1) {
        meetingRecords.value.splice(index, 1)
        message.success('记录已删除')
        // 注意：这里不修改统计数据，因为统计数据来自后端
      }
    },
  })
}

// ============ 数据加载 ============
// 加载日程数据
const loadSchedules = async () => {
  try {
    schedulesData.value = await scheduleApi.getSchedules()
  } catch (error: any) {
    console.error('加载日程失败:', error)
  }
}

// 加载已删除的日程数据
const loadDeletedSchedules = async () => {
  try {
    deletedSchedulesData.value = await scheduleApi.getDeletedSchedules()
  } catch (error: any) {
    console.error('加载已删除日程失败:', error)
  }
}

// 加载纪念日数据
const loadAnniversaries = async () => {
  try {
    anniversariesData.value = await anniversaryApi.getAnniversaries()
  } catch (error: any) {
    console.error('加载纪念日失败:', error)
  }
}

// 加载见面计划数据
const loadMeetingData = async () => {
  try {
    const [countdowns, relationshipStats] = await Promise.all([
      countdownApi.getCountdowns(),
      relationshipApi.getRelationshipStats(),
    ])

    // 获取"见面"类型的倒计时
    meetingCountdownData.value =
      countdowns.find((c: Countdown) => c.type === '见面') || countdowns[0] || null

    // 获取恋爱统计
    relationshipStatData.value = relationshipStats[0] || null
  } catch (error: any) {
    console.error('加载见面数据失败:', error)
  }
}

// 加载所有数据
const loadAllData = async () => {
  loading.value = true
  try {
    await Promise.all([
      loadSchedules(),
      loadDeletedSchedules(),
      loadAnniversaries(),
      loadMeetingData(),
    ])
  } catch (error: any) {
    console.error('加载数据失败:', error)
    message.error('加载数据失败')
  } finally {
    loading.value = false
  }
}

// 启动见面倒计时定时器
const startMeetingTimer = () => {
  meetingTimer = window.setInterval(() => {
    // 强制重新计算 computed
    if (meetingCountdownData.value) {
      meetingCountdownData.value = { ...meetingCountdownData.value }
    }
  }, 60000) // 每分钟更新一次
}

// 组件挂载时加载数据
onMounted(async () => {
  await loadAllData()
  startMeetingTimer()
})

// 组件卸载时清除定时器
onUnmounted(() => {
  if (meetingTimer) {
    clearInterval(meetingTimer)
  }
})
</script>
